package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import offer.GetDataSource;
import offer.SessionObj;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.netscenery.yang.designer.Action;
import com.netscenery.yang.model.*;
import com.netscenery.yang.writer.YangFormatter;

import system.bean.DocRelation;
import system.bean.Member;
import system.bean.ModuleDocument;
import system.dao.DocRelationDao;
import system.dao.DocumentDao;

public class FileUploadServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public FileUploadServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset = utf-8");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	@SuppressWarnings({ "deprecation", "static-access" })
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out   = response.getWriter();
		
		SessionObj sessionObj = (SessionObj)request.getSession().getAttribute("sessionObj");
		Member member = sessionObj.getMember();
		
		int relyOnDocmentId      = 0;
		String relyOnDocmentIds  ="";
		DocumentDao documentDao  = new DocumentDao();
		ModuleDocument mDocument = new ModuleDocument();

		Action uploadAxtion = new Action();
		Module module      = null;
		/**
		 * *********************************************************************************************
		 * ��ȡ�ϴ��ļ�
		 */
		DiskFileItemFactory itemFactory = new DiskFileItemFactory();              //���̶���
		String path = getServletContext().getRealPath("/fileStore/tempUpload");   //��ȡ�ļ�Ҫ�����Ŀ¼
		itemFactory.setRepository(new File(path));                                //������ʱĿ¼
		itemFactory.setSizeThreshold(1024*8);                                     //8k�Ļ�����,�ļ�����8K�򱣴浽��ʱĿ¼
		ServletFileUpload upload = new ServletFileUpload(itemFactory);            //�������request�Ķ���
		upload.setHeaderEncoding("utf-8");                                //�����ļ�������
		upload.setFileSizeMax(1024 * 1024 * 5);                           // ����ÿ���ļ����Ϊ5M
		upload.setSizeMax(1024 * 1024 * 10);                              // һ��������ϴ�10M
		String fileType = "xml";
		try {
			List<FileItem> list = upload.parseRequest(request);           // ����
			for (FileItem fileItem : list) {
				if (!fileItem.isFormField()) {
					if(fileItem.getFieldName().equalsIgnoreCase("xmlDocName")){
						String docName = fileItem.getName();
						if(docName.endsWith(".yin")){
							fileType = uploadAxtion.FORMAT_YIN;
						}else if(docName.endsWith(".yang")){
							fileType = uploadAxtion.FORMAT_YANG;
						}
						docName = docName.substring(docName.lastIndexOf("\\") + 1);
						docName = docName.substring(0,docName.indexOf("."));
						mDocument.setDisplayName(docName);
						mDocument.setDocContent(fileItem.getString("utf-8"));
						mDocument.setMemberId(member.getMemberId());
					}
				}else{
					if(fileItem.getFieldName().equalsIgnoreCase("_RelyOnFileIDs")){
						relyOnDocmentIds = fileItem.getString();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		/**
		 * *********************************************************************************************
		 */
		String msgString = "";
		boolean isRelyOnFlies = false;
		//��5�ļ�����
		if(!"".equalsIgnoreCase(relyOnDocmentIds)&&!"-1".equalsIgnoreCase(relyOnDocmentIds)){
			isRelyOnFlies = true;
		}
		ArrayList<Module> relatedModules = new ArrayList<Module>();
		if(isRelyOnFlies){
			String[] relayIdList = relyOnDocmentIds.split(",");
			for(int i = 0 ; i < relayIdList.length ; i++ ){
				String relayId= relayIdList[i];
				String[] idDetail= relayId.split("@");
				if (idDetail.length != 2){
					return;
				}
				
				relyOnDocmentId = Integer.parseInt(idDetail[0]);
				String type = idDetail[1];
				if(-1 != relyOnDocmentId && 0 != relyOnDocmentId){
					Module tempmodule = null;
					if (type.equals("pub")){
						tempmodule   = GetDataSource.openFileModule(relyOnDocmentId);
					}
					else if (type.equals("user")){
						tempmodule = GetDataSource.GetModuleByDocId(relyOnDocmentId);
					}

					relatedModules.add(tempmodule);
				}
			}
		}
		//module = uploadAxtion.importModule(fileType, mDocument.getDocContent(), relatedModules);
		module = uploadAxtion.openModule(fileType, mDocument.getDocContent(), relatedModules);
		Validator validator = null;
		if(null != module){
			validator = module.validate();
			if(!validator.isValid()){
				module = null;
			}
		}
		
		/**
		 * �ļ����
		 */
		String url = "/GoToIndexServlet";
		if( null == module){
			url = "/Notice.jsp";
			String source = "GoToIndexServlet";
			request.setAttribute("source", source);
			msgString = "Failed to parse this document!";
			request.setAttribute("msg", msgString);
			request.setAttribute("validator", validator);
			
		}else{
			mDocument.setDocName(module.getName());
			if(documentDao.isMemberDocExist(mDocument)){
				msgString = "Duplicate document!";
			}else{
				if(module instanceof MainModule){
					mDocument.setDocType("MainModule");
				}else if(module instanceof SubModule){
					mDocument.setDocType("SubModule");
				}
				YangFormatter formatter = new YangFormatter();
				formatter.setPrettyFormatter();
				mDocument.setDocContent(module.toYANGString(formatter));
				documentDao.insert(mDocument);
				msgString = "This document has been imported successfully!";
			}
		}
		/**
		 * �ļ�����5��ϵ���
		 */
		if((null!=module) && (isRelyOnFlies)){
			mDocument = documentDao.getMemberDocument(mDocument.getMemberId(), mDocument.getDocName());
			mDocument.setDependFileIds(relyOnDocmentIds);
			documentDao.update(mDocument);
		}
		request.setAttribute("msgString", msgString);
		
		ServletContext sc=this.getServletContext();
		RequestDispatcher rd=sc.getRequestDispatcher(url);
		rd.forward(request, response);
		
		
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
